package cn.sangyy.gift.service.impl;

import cn.sangyy.gift.client.LoginUserClient;
import cn.sangyy.gift.common.util.AjaxResult;
import cn.sangyy.gift.common.util.PageList;
import cn.sangyy.gift.common.util.code.CodeEnum;
import cn.sangyy.gift.domain.Employee;
import cn.sangyy.gift.domain.LoginUser;
import cn.sangyy.gift.domain.Tenant;
import cn.sangyy.gift.dto.TenantRegisterDto;
import cn.sangyy.gift.exception.GiftAssert;
import cn.sangyy.gift.mapper.EmployeeMapper;
import cn.sangyy.gift.mapper.TenantMapper;
import cn.sangyy.gift.query.TenantQuery;
import cn.sangyy.gift.service.ITenantService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sangyangyang
 * @since 2023-03-23
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginUserClient loginUserClient;

    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());
        //自己写查询条件实现多表关联查询和高级查询
        List<Tenant> rows = tenantMapper.selectPageList(page,query);
        return new PageList(page.getTotal(), rows);
    }

    @Override
    public Tenant getById(Long id) {
        return tenantMapper.getById(id);
    }

    @Override
    //@Transactional
    @GlobalTransactional //开启全局事务
    public AjaxResult settlement(TenantRegisterDto tenantRegisterDto) {
        //1.参数校验
        validate(tenantRegisterDto);
        Employee admin = tenantRegisterDto.getAdmin();
        Tenant tenant = tenantRegisterDto.getTenant();
        Long mealId = tenantRegisterDto.getMealId();
        //5.@TODO 百度的人工只能审查审核租户信息

        //6.先添加管理员信息，因为管理员有登录id，所以先添加登录信息获取登录id
        //远程调用授权中心获取登录id
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(admin,loginUser);
        loginUser.setType(1);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        if(ajaxResult.getCode()==201){
            return ajaxResult;
        }
        Long loginId = Long.valueOf(ajaxResult.getResultObj().toString());
        admin.setState(0);
        admin.setLoginId(loginId);
        admin.setInputTime(new Date());
        employeeMapper.insert(admin);
        //7.添加租户
        tenant.setAdminId(admin.getId());
        tenant.setRegisterTime(new Date());
        tenantMapper.insert(tenant);
        //8.添加套餐和租户关联表
        HashMap<String,Object> params = new HashMap<>();
        params.put("tenantId",tenant.getId());
        params.put("mealId",mealId);
        params.put("expireDate", DateUtils.addYears(new Date(),1));
        tenantMapper.adTenantMeal(params);
        //9. @TODO 发送激活管理员邮件

        //10. @TODO 在激活邮件的地方发送邮箱或者短信提示用户入住成功，可以正常登录使用

//        int i = 1/0;
        return AjaxResult.me().setMessage("入驻成功");
    }

    private void validate(TenantRegisterDto tenantRegisterDto){
//        GiftAssert.assertNotNull(tenantRegisterDto);
//        Employee admin = tenantRegisterDto.getAdmin();
//        Tenant tenant = tenantRegisterDto.getTenant();
//        Long mealId = tenantRegisterDto.getMealId();
//        GiftAssert.assertNotNull(mealId); //上面几行用了jrs303校验了
        Employee admin = tenantRegisterDto.getAdmin();
        Tenant tenant = tenantRegisterDto.getTenant();
        //2.两次密码确认
        GiftAssert.assertStrEquals(admin.getPassword(),admin.getConfirmPassword(), CodeEnum.TWO_PASSWORD_ERROR);
        //3.判断租户是否存在 存在不能再次入住
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", tenant.getCompanyName()));
        GiftAssert.assertListIsNull(tenants,CodeEnum.TENANT_EXIST_ERROR);
        //4.判断租户管理员是否存在,存在则提示登录后添加租户
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username", admin.getUsername()));
        GiftAssert.assertListIsNull(employees,CodeEnum.TENANT_EMPLOYEE_EXIST_ERROR);
    }
}
